﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using DevExpress.Data.Filtering;
using DevExpress.ExpressApp;
using DevExpress.ExpressApp.Security;
using DevExpress.ExpressApp.Security.Strategy;
using DevExpress.Persistent.BaseImpl;
using L4Alive.Module.BusinessObjects;

namespace L4Alive.Module.Controllers
{
    /// <summary>
    /// autentifikace usivatele
    /// </summary>
    /// <remarks>
    /// ...
    /// 23.1.2014 SL; modifkace - uzivatelske parvo
    /// </remarks>
    public class CustomAuthentication : AuthenticationBase, IAuthenticationStandard
    {
        private L4_UTIL_APP_RUNNING iID_L4_UTIL_APP_RUNNING;
        /// <summary>
        /// id v L4_UTIL_APP_RUNNING
        /// </summary>
        public L4_UTIL_APP_RUNNING ID_L4_UTIL_APP_RUNNING
        {
            get
            {
                return iID_L4_UTIL_APP_RUNNING;
            }
            set
            {
                iID_L4_UTIL_APP_RUNNING = value;
            }
        }

        private CustomLogonParameters logonParameters;
        public CustomAuthentication()
        {
            logonParameters = new CustomLogonParameters();
        }
        public override void Logoff()
        {
            base.Logoff();
            logonParameters = new CustomLogonParameters();
        }
        public override void ClearSecuredLogonParameters()
        {
            logonParameters.Password = "";
            base.ClearSecuredLogonParameters();
        }

        private void NeuspesnePrihlaseni(IObjectSpace os)
        {
        }

        /// <summary>
        /// uyivatelska autentifikace
        /// </summary>
        /// <param name="objectSpace"></param>
        /// <returns></returns>
        /// <remarks>
        /// ...
        /// 23.1.2014 SL; ymena v overeni prava, ...
        /// </remarks>
        public override object Authenticate(IObjectSpace objectSpace)
        {
            CustomLogonParameters customLogonParameters =
                logonParameters as CustomLogonParameters;


            customLogonParameters.user = objectSpace.FindObject<SecuritySystemUser>(new BinaryOperator("UserName", customLogonParameters.UserName, BinaryOperatorType.Equal));
            if (customLogonParameters.user == null)
            {
                throw new AuthenticationException(customLogonParameters.UserName, "Error");

            }
            if (!customLogonParameters.user.ComparePassword(
                customLogonParameters.Password))
            {
                throw new AuthenticationException(customLogonParameters.user.UserName, "Error");
            }

            if (!false) // user right MultiLogin
            {
                if (this.IsUserAuthenticate(objectSpace, customLogonParameters))
                {
                    throw new AuthenticationException(customLogonParameters.user.UserName, "Error");
                }
            }
            // zalozim objekt autentifikace
            iID_L4_UTIL_APP_RUNNING = objectSpace.CreateObject<L4_UTIL_APP_RUNNING>();
            iID_L4_UTIL_APP_RUNNING.Save();


            //ulozimi si info o multi prihlaseni 
            if (!false)
            {
                if (iID_L4_UTIL_APP_RUNNING.ID_L4_UTIL_APP_RUNNING == 0)
                {
                    IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());

                    NastavPrvni(customLogonParameters.user, System.Environment.MachineName, host.AddressList[host.AddressList.Length - 1].ToString(), System.Environment.UserName);

                }
            }

            objectSpace.CommitChanges();

            return objectSpace.FindObject<SecuritySystemUser>(new BinaryOperator("UserName", customLogonParameters.UserName));
        }

        /// <summary>
        /// nastaveni prvniho pripojeni 
        /// </summary>
        /// <param name="user"></param>
        /// <param name="sMachineName"></param>
        /// <param name="IP"></param>
        /// <param name="sUserName"></param>
        /// <param name="id_l4_cis_pracoviste"></param>
        private void NastavPrvni(SecuritySystemUser user, string sMachineName, string IP, string sUserName)
        {
            iID_L4_UTIL_APP_RUNNING.ID_L4_User = user;
            iID_L4_UTIL_APP_RUNNING.JE_PRIHLASEN = true;
            iID_L4_UTIL_APP_RUNNING.POCITAC = sMachineName;
            iID_L4_UTIL_APP_RUNNING.POCITAC_IP = IP;
            iID_L4_UTIL_APP_RUNNING.LOGIN_OS = sUserName;
            ID_L4_UTIL_APP_RUNNING.Save();
        }
        public override IList<Type> GetBusinessClasses()
        {
            return new Type[] { typeof(CustomLogonParameters) };
        }
        public override bool AskLogonParametersViaUI
        {
            get { return true; }
        }
        public override object LogonParameters
        {
            get { return logonParameters; }
        }
        public override bool IsLogoffEnabled
        {
            get { return true; }
        }

        /// <summary>
        /// zjisteni jestli lze prihlasit 
        /// </summary>
        /// <param name="os"></param>
        /// <returns></returns>
        /// <remarks>
        /// ...
        /// 19.12.2013 SL;
        /// </remarks>
        //private L4_UTIL_APP_RUNNING AuthenticateUserMulti(IObjectSpace os, CustomLogonParameters customLogonParameters)
        protected bool IsUserAuthenticate(IObjectSpace os, CustomLogonParameters customLogonParameters)
        {
            try
            {
                int iMinutes = 10;
                //if (System.Configuration.ConfigurationManager.AppSettings["DELAY_APP_RUNING"] == null ||
                //                     System.Configuration.ConfigurationManager.AppSettings["DELAY_APP_RUNING"].ToString() == "")
                //    iMinutes = 10;
                //else
                //    iMinutes = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["DELAY_APP_RUNING"]);


                L4_UTIL_APP_RUNNING xpcol = os.FindObject<L4_UTIL_APP_RUNNING>(CriteriaOperator.Parse("[ID_L4_User.UserName]=? and [JE_PRIHLASEN]=true and isnull([DT_ODHLASENI]) and [DT_APP_RUNNING]>= ? and [POCITAC]<>?", customLogonParameters.user.UserName, DateTime.Now.AddMinutes(-1 * iMinutes), System.Environment.MachineName));

                if (xpcol != null)
                {
                    return true;   // je prihlasen
                }

                return false;   // neni prihlasen
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
